﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Gasco.Business.Services;
using Gasco.DataAccess;
using System.Web.Services;
using System.Text;
using System.Collections.Generic;

public partial class Controls_origin_add : System.Web.UI.UserControl
{
    protected void Page_Init(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LookupService<country> service = new LookupService<country>();
            ddCountry.DataSource = service.GetAll();
            ddCountry.DataBind();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["id"] != null)
        {
            if (!Page.IsPostBack)
            {
                ProductService service = new ProductService();
                CityService cityService = new CityService();

                origin o = service.GetOriginById(Convert.ToInt32(Request.QueryString["id"]));
                city c = cityService.GetCity(o.city_id);
                List<city> listcity = (List<city>)cityService.GetCitiesByCountry(c.country_id);

                tbRefineryName.Text = o.refinery;                
                ddCountry.SelectedValue = c.country_id.ToString();
                ddCity.DataSource = listcity;
                ddCity.DataBind();
                ddCity.SelectedValue = o.city_id.ToString();
            }
        }
    }

    protected void btnclose_Click(object sender, EventArgs e)
    {
        InsertUpdateInfo();
        Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script1", "<script>pageClose();</script>");
    }


    private void InsertUpdateInfo()
    {
        bool InsertMode = (Request.QueryString["id"] == null);

        ProductService service = new ProductService();
        CityService cityService = new CityService();
        origin o;

        if (InsertMode)
        {
            o = new origin();
        }
        else
        {
            o = service.GetOriginById(Convert.ToInt32(Request.QueryString["ID"]));
        }
        o.refinery = tbRefineryName.Text;
        o.city_id = Convert.ToInt32(cityHidden.Value);
        o.update_date = DateTime.Now;
        if (InsertMode)
        {
            o.create_date = DateTime.Now;
            service.CreateOrigin(o);
        }
        else
        {
            service.UpdateOrigin(o);
        }
    }
}
